package com.etrans.web.gps.business.gis.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etrans.egov.base.intf.ObjDriver;
import com.etrans.egov.base.intf.TIntfObjTrack;
import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.base.domain.VehicleVo;
import com.etrans.web.gps.business.gis.domain.Track;
import com.etrans.web.gps.business.system.service.CommonService;
import com.etrans.web.gps.timer.LocalCache;
import com.etrans.web.gps.util.Config;
import com.etrans.web.gps.util.EgovUtil;
import com.etrans.web.gps.util.map.GpsToGaoDe;

/**
 * 定位服务-业务层
 *
 * @author jw.chen
 */
@Service
public class MonitorService extends BaseService {
    @Autowired
    private EgovUtil egovUtil;
    
    @Autowired
    private CommonService commonService;
    
	@Autowired  
    private Config config; //引用统一的参数配置类  

	//获取上线车辆集合
	Set<String> onlineList = null;
	
    /**
     * 获取定位树
     *
     * @param param
     * @return
     * @throws Exception 
     */
    public List<HashMap<String, Object>> getMonitorTreeJsonResult(Map<String, Object> param) throws Exception {
    	long start = System.currentTimeMillis();
    	
    	int user_area_id = (int)param.get("area_id");
    	String user_fullID = (String)param.get("fullID");
    	//监控树
    	List<HashMap<String, Object>> monitorTree = new ArrayList<HashMap<String,Object>>();
    	//树节点
    	HashMap<String, Object> monitorNode = null;
    	//所有上线车辆集合
		onlineList = LocalCache.onlineVehicles.get("online");
    	//省级节点
    	List<HashMap<String, Object>> firstNode = new ArrayList<HashMap<String,Object>>();
    	//市级节点
    	List<HashMap<String, Object>> secondNode = new ArrayList<HashMap<String,Object>>();
    	//区县节点
    	List<HashMap<String, Object>> thirdNode = new ArrayList<HashMap<String,Object>>();
    	
    	//获取所有区域节点
    	List<HashMap<String, Object>> treeNode = this.selectList("monitorMapper.queryTreeNode", param);
    	for (HashMap<String, Object> hashMap : treeNode) {
    		int level = (int)hashMap.get("Level");
    		if(level == 1){
    			firstNode.add(hashMap);
    		}else if(level == 2){
    			secondNode.add(hashMap);
    		}else if(level == 3){
    			thirdNode.add(hashMap);
    		}
    	}
    	
    	//区域下的业户集合
    	HashMap<Integer,List<HashMap<String, Object>>> area_Ent_Map = new HashMap<Integer,List<HashMap<String, Object>>>();
    	List<HashMap<String, Object>> ent_List = commonService.queryEnterAndPlatByRoleNotLimit(user_area_id,null);
    	for (HashMap<String, Object> hashMap : ent_List) {
			int areaId = (int)hashMap.get("areaId");
			List<HashMap<String, Object>> area_Ent_List = area_Ent_Map.get(areaId);
			if(area_Ent_List == null || area_Ent_List.size() <= 0){
				area_Ent_List = new ArrayList<HashMap<String, Object>>();
			}
			area_Ent_List.add(hashMap);
			area_Ent_Map.put(areaId, area_Ent_List);
		}
    	
    	//业户下对应的车集合
    	HashMap<Integer,List<HashMap<String, Object>>> ent_Vehicle_Map = new HashMap<Integer,List<HashMap<String, Object>>>();
    	//每个区域节点对应的车辆
    	HashMap<String,List<HashMap<String, Object>>> first_Vehicle_Map = new HashMap<String,List<HashMap<String, Object>>>();
    	HashMap<String,List<HashMap<String, Object>>> second_Vehicle_Map = new HashMap<String,List<HashMap<String, Object>>>();
    	HashMap<String,List<HashMap<String, Object>>> third_Vehicle_Map = new HashMap<String,List<HashMap<String, Object>>>();
    	
    	HashMap<String,Object> params = new HashMap<String, Object>();
		params.put("fullID", String.format("%08d",user_area_id));
    	List<HashMap<String,Object>> vehicles_list = commonService.queryVeListByRole(params);
    	for (HashMap<String, Object> hashMap : vehicles_list) {
    		//按业户分组
    		int enterprise_id = Integer.valueOf(hashMap.get("enterprise_id")+"");
    		List<HashMap<String, Object>> ent_Vehicle_List = ent_Vehicle_Map.get(enterprise_id);
			if(ent_Vehicle_List == null || ent_Vehicle_List.size() <= 0){
				ent_Vehicle_List = new ArrayList<HashMap<String, Object>>();
			}
			ent_Vehicle_List.add(hashMap);
			ent_Vehicle_Map.put(enterprise_id, ent_Vehicle_List);
			
			//按区域
			String fullID = (String)hashMap.get("fullID");
			if(fullID != null && !"".equals(fullID)){
				//省份节点
				String first = fullID.substring(0, 8);
				List<HashMap<String, Object>> first_Vehicle_List = first_Vehicle_Map.get(first);
				if(first_Vehicle_List == null || first_Vehicle_List.size() <= 0){
					first_Vehicle_List = new ArrayList<HashMap<String, Object>>();
				}
				first_Vehicle_List.add(hashMap);
				first_Vehicle_Map.put(first, first_Vehicle_List);
				if(fullID.length()>=18){
					//城市节点
					String second = fullID.substring(0, 17);
					List<HashMap<String, Object>> second_Vehicle_List = second_Vehicle_Map.get(second);
					if(second_Vehicle_List == null || second_Vehicle_List.size() <= 0){
						second_Vehicle_List = new ArrayList<HashMap<String, Object>>();
					}
					second_Vehicle_List.add(hashMap);
					second_Vehicle_Map.put(second, second_Vehicle_List);
					//区县节点
					List<HashMap<String, Object>> third_Vehicle_List = third_Vehicle_Map.get(fullID);
					if(third_Vehicle_List == null || third_Vehicle_List.size() <= 0){
						third_Vehicle_List = new ArrayList<HashMap<String, Object>>();
					}
					third_Vehicle_List.add(hashMap);
					third_Vehicle_Map.put(fullID, third_Vehicle_List);
				}
					
			}
		}
    	
    	//第一级：省份
    	for (HashMap<String, Object> fristNodeMap : firstNode) {
    		monitorNode = new HashMap<String, Object>();
    		//拼接节点元素
    		String first_ID = String.valueOf(fristNodeMap.get("ID"));
    		String first_Name = String.valueOf(fristNodeMap.get("Name"));
    		String first_FullID = String.valueOf(fristNodeMap.get("FullID"));
			
    		monitorNode.put("ID", first_ID);
    		monitorNode.put("NAME", first_Name + nodeVehicles(first_Vehicle_Map.get(first_FullID)));
    		monitorNode.put("PID", "-1");
    		monitorNode.put("LEVEL", "1");
    		monitorNode.put("open", true);		//默认展开
    		monitorTree.add(monitorNode);
    		
    		//第二级：城市
    		for (HashMap<String, Object> secondNodeMap : secondNode) {
    			monitorNode = new HashMap<String, Object>();
    			//拼接节点元素
    			String second_ID = String.valueOf(secondNodeMap.get("ID"));
    			String second_Name = String.valueOf(secondNodeMap.get("Name"));
    			String second_FullID = String.valueOf(secondNodeMap.get("FullID"));
				
    			if(second_FullID.equals(first_FullID+"."+String.format("%08d",Integer.parseInt(second_ID))) && (user_fullID.length() == 8 ? second_FullID.contains(user_fullID) : second_FullID.contains(user_fullID.substring(0, 17)))){
    				monitorNode.put("ID", second_ID);
    				monitorNode.put("NAME", second_Name + nodeVehicles(second_Vehicle_Map.get(second_FullID)));
    				monitorNode.put("PID", first_ID);
    				monitorNode.put("LEVEL", 2);
    				monitorTree.add(monitorNode);
    				
    				//第三级：区县
    				for (HashMap<String, Object> thirdNodeMap : thirdNode) {
    					monitorNode = new HashMap<String, Object>();
    					//拼接节点元素
    					String third_ID = String.valueOf(thirdNodeMap.get("ID"));
    					String third_Name = String.valueOf(thirdNodeMap.get("Name"));
    					String third_FullID = String.valueOf(thirdNodeMap.get("FullID"));
    					
    					if(third_FullID.equals(second_FullID+"."+String.format("%08d",Integer.parseInt(third_ID))) && third_FullID.contains(user_fullID)){
    						monitorNode.put("ID", third_ID);
        					monitorNode.put("NAME", third_Name + nodeVehicles(third_Vehicle_Map.get(third_FullID)));
        					monitorNode.put("PID", second_ID);
        					monitorNode.put("LEVEL", 3);
        					monitorTree.add(monitorNode);
        					
        					//第四级：业户信息
        					List<HashMap<String, Object>> enterpriseList = area_Ent_Map.get(Integer.parseInt(third_ID));
        					if(enterpriseList != null && enterpriseList.size() > 0){
        						for (HashMap<String, Object> enterprise : enterpriseList) {
        							monitorNode = new HashMap<String, Object>();
        							//拼接节点元素
        							String enterpriseID = String.valueOf(enterprise.get("entId"));
        							String enterpriseName = String.valueOf(enterprise.get("entName"));
        							String PF_Name = String.valueOf(enterprise.get("platName"));
        							
        							monitorNode.put("ID", "ent_"+enterpriseID);
        							monitorNode.put("NAME", enterpriseName + nodeVehicles(ent_Vehicle_Map.get(Integer.parseInt(enterpriseID))));
        							monitorNode.put("PID", third_ID);
        							monitorNode.put("PF_Name", PF_Name);
        							monitorNode.put("LEVEL", 4);
        							monitorTree.add(monitorNode);
        						}
        					}
        				}
    				}
    			}
    		}
		}
    	//清空临时变量
    	treeNode = null;
    	area_Ent_Map = null;
    	ent_Vehicle_Map = null;
    	first_Vehicle_Map = null;
    	second_Vehicle_Map = null;
    	third_Vehicle_Map = null;
    	firstNode = null;
    	secondNode = null;
    	thirdNode = null;
    	onlineList = null;
    	
    	long end = System.currentTimeMillis();
    	System.out.println("=============监控树查询用时：" + (end-start)/1000 + "." + (end-start)%1000 + "秒==============");
    	return monitorTree;
    }
    
    /**
     * 获取节点下的车辆(在线数/入网总数)
     * @param vehicles
     * @return
     * @throws Exception
     */
    public String nodeVehicles(List<HashMap<String,Object>> vehicles) throws Exception{
		int vehicleOnline = 0;	//业户下在线车辆数
		int vehicleAll = 0;		//业户下所有车辆
		//车辆集合
		if(vehicles != null && vehicles.size() > 0){
			//遍历所有车，取当前节点下在线的车
			for (int i = 0; i < vehicles.size(); i++) {
				HashMap<String,Object> hashMap = vehicles.get(i);
				if(hashMap != null){
					vehicleAll++;
					String vehicle_no = String.valueOf(hashMap.get("vehicle_no"));
					String vehicle_color = String.valueOf(hashMap.get("vehicle_color"));
					//判断有权限的车是否在线
					String vehicle_no_color = String.format("%s_%s", vehicle_no, vehicle_color);
					if(onlineList != null && onlineList.contains(vehicle_no_color)){
						vehicleOnline++;
					}
				}
			}
		}
		return "(" + vehicleOnline + "/" + vehicleAll + ")";
    }
    
    /**
     * 业户查询车辆
     * @param param
     * @return
     */
    public List<HashMap<String,Object>> queryVehicleByEnt(Map<String, Object> param) {
    	return selectList("monitorMapper.queryVehicleByEnt", param);
    }
    
//    /**
//     * 定位页面查询结果数
//     *
//     * @param param
//     * @return
//     */
//    public Integer queryVehicleByConditionCount(Map<String, Object> param) {
//        Integer totalRow = selectOne("vehicleMapper.queryVehicleByConditionCount", param);
//        return totalRow;
//    }

    /**
     * 定位页面模糊查询车辆
     * @param area_id		用户所管辖的区域
     * @param vehicle_no	车牌号
     * @return
     * @throws Exception
     */
    public List<HashMap<String, Object>> queryVehicleByCondition(HashMap<String,Object> param) throws Exception {
    	return commonService.queryVeListByRole(param);
    }

    /**
     * 根据车辆集获取车辆ids
     *
     * @param vehicles
     * @return
     */
    public List<Integer> getVehicleIds(List<VehicleVo> vehicles) {
        List<Integer> vehicleIds = new ArrayList<Integer>(); //获取在线车IDS
        for (VehicleVo v : vehicles) {
            vehicleIds.add(v.getVehicleId());
        }
        return vehicleIds;
    }

    /**
     * 根据车辆集获取车辆CommNos  通信号
     *
     * @param vehicles
     * @return
     */
    public String[] getCommNos(List<VehicleVo> vehicles) {
        String[] anArray = new String[vehicles.size()];
        for (int i = 0; i < vehicles.size(); i++) {
            if (vehicles.get(i).getCommNo() != null) {
                anArray[i] = vehicles.get(i).getCommNo();
            } else {
                anArray[i] = "NULL";
            }
        }
        return anArray;
    }

  

    /**
     * 根据车牌号_车牌颜色，从服务端获取定位数据
     * @return
     * @throws Exception
     */
    public List<Track> getSubScribe(String[] vehicle_no_color) throws Exception {
        List<Track> result = new ArrayList<Track>();
        List<TIntfObjTrack> resTrack = egovUtil.getTrack(vehicle_no_color);
        for (TIntfObjTrack objTrack : resTrack) {
            if (objTrack != null) {
                Track track = new Track();
                track.setVehicleNo(objTrack.getVehicleNo());
                track.setVehicleColor(objTrack.getVehicleColor());
                track.setVehicleId(objTrack.getVehicleId());
                track.setLongitudeD(objTrack.getLongitudeD());
                track.setLatitudeD(objTrack.getLatitudeD());
                if (objTrack.getValid()) {
                    track.setValidS("定位");
                } else {
                    track.setValidS("盲区");
                }
                if (objTrack.getLatitudeD() != 0 && objTrack.getLongitudeD() != 0) {
                    double[] gdLatlon = GpsToGaoDe.transform(objTrack.getLatitudeD(), objTrack.getLongitudeD());
                    track.setLatitude(gdLatlon[0]);
                    track.setLongitude(gdLatlon[1]);
                }
                track.setGpsTimeS(objTrack.getGpsTimeS());
                track.setGpsMileage(objTrack.getMileage());
                track.setGpsSpeedF(objTrack.getGpsSpeed());
                track.setPulseSpeedF(objTrack.getPulseSpeed());
                track.setHead(objTrack.getDirection());
                track.setValid(objTrack.getValid());
                track.setAccStatus(objTrack.getAccON());
                if (objTrack != null && objTrack.getGpsTimeS() != null) {   // 1.开车 2 停车  3离线       4 报警(去掉)
                    long diff = System.currentTimeMillis() - objTrack.getGpsTime();
                    if (Math.abs(diff) < 1000 * 60 * 10) {
                        if (objTrack.getGpsSpeed() > 0) {
                            track.setCarStatus(1);
                        } else {
                            track.setCarStatus(2);
                        }
                    } else {
                        track.setCarStatus(3);
                    }
                }
                result.add(track);
            }
        }
        return result;
    }

    /**
     * 获取在线车辆
     * @param vehicles 车辆集
     * @throws Exception
     */
    public List<String> getOnlineVehicle(List<HashMap<String,Object>> vehicles) throws Exception {
    	List<String> online = new ArrayList<String>();
    	
    	if(vehicles != null && vehicles.size() > 0){
    		Set<String> onlineVehicles = LocalCache.onlineVehicles.get("online");
    		if(onlineVehicles != null && onlineVehicles.size() > 0){
    			for (int i = 0; i < vehicles.size(); i++) {
    				String vehicle_no = String.valueOf(vehicles.get(i).get("vehicle_no"));
    				String vehicle_color = String.valueOf(vehicles.get(i).get("vehicle_color"));
    				//车牌号_车牌颜色
    				String vehicle_no_color = String.format("%s_%s", vehicle_no, vehicle_color);
    				
    				if(onlineVehicles.contains(vehicle_no_color)){
    					online.add(vehicle_no_color);
    				}
    			}
    		}
    	}
		return online;
    }
    
    /**
     * 获取车辆上下线状态
     * @param vehicles
     * @return
     * @throws Exception
     */
    public List<String> queryVehicleStatus(String[] vehicle_no_color) throws Exception {
    	List<String> online = new ArrayList<String>();
    	//获取在线车辆
    	Set<String> onlineVehicles = LocalCache.onlineVehicles.get("online");
    	if(onlineVehicles != null && onlineVehicles.size() > 0){
    		for (String val : vehicle_no_color) {
    			if(onlineVehicles.contains(val)){
    				online.add(val);
    			}
    		}
    	}
    	return online;
    }
    
    /**
     * 获取当前司机信息
     * @param vehicle_no_color   车牌号_车牌颜色
     * @return
     * @throws Exception
     */
    public ObjDriver queryDriverInfo(String[] vehicle_no_color) throws Exception{
    	ObjDriver objDriver = egovUtil.getDriverInfo(vehicle_no_color[0]);
    	if(objDriver != null){
    		HashMap<String, Object> param = new HashMap<String, Object>();
    		param.put("licence", objDriver.getLicence());
    		HashMap<String, Object> driver = this.selectOne("monitorMapper.queryDriverInfo", param);
    		if(driver != null){
    			objDriver.setImgUrl(config.imagePath + String.valueOf(driver.get("img_url")));
    		}else{
    			objDriver.setImgUrl("");
    		}
    	}
    	return objDriver;
    }

	public List<HashMap<String, Object>> queryVeList(Integer area_id) {
		Map<String,Object> param = new HashMap<>();
		param.put("FullID",String.format("%08d", area_id));
		return this.selectList("monitorMapper.queryVeList", param);
	}

	/**
	 * @Description 获取当前部署地点的地址信息
	 * @return
	 */
	public HashMap<String, Object> queryDeploymentAreaInfo(String area_code) {
		return this.selectOne("monitorMapper.queryDeploymentAreaInfo", area_code);
	}

}
